package com.rzico.sbl.ui.mine

import android.Manifest
import android.annotation.SuppressLint
import android.os.Build
import androidx.activity.result.ActivityResultLauncher
import androidx.core.view.isVisible
import com.amap.api.AMapLocationHelper
import com.lzy.okgo.OkGo
import com.lzy.okgo.utils.OkLogger
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivitySettingBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.other.GlideCacheUtil
import com.rzico.sbl.other.userRole
import com.rzico.sbl.ui.LoginActivity
import com.rzico.sbl.ui.WebActivity
import com.rzico.sbl.viewmodel.UpdateViewModel
import com.tim.library.logout
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.*
import com.xinnuo.common.helper.AppSettingHelper.goIntentSetting
import com.xinnuo.common.manager.LocationManager
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.utils.showHintDialog
import com.xinnuo.common_ui.utils.showOneHintDialog
import com.xinnuo.common_ui.viewmodel.BaseViewModel
import com.xinnuo.objectbox.getBox
import com.xinnuo.objectbox.getBoxEuery
import com.xinnuo.objectbox.model.AppLoginData
import com.xinnuo.objectbox.model.AppLoginData_

class SettingActivity : BaseActivity(R.layout.activity_setting) {

    private val mBinding by lazy { ActivitySettingBinding.bind(getRootView()) }

    override fun getViewModel() = get<UpdateViewModel>()

    private lateinit var mLauncherCall: ActivityResultLauncher<String>
    private lateinit var mLauncher1: ActivityResultLauncher<Array<String>>
    private lateinit var mLauncher2: ActivityResultLauncher<String>

    private var mAppData: AppLoginData? = null

    override fun initData() {
        setTransparentAndToolbar()

        initLayout()
        initLauncher()
    }

    private fun initLayout() {
        mBinding.apply {
            settingLocationLl.isVisible = userRole in "1,2,3,4,7,10"
            settingCallLl.isVisible =
                userRole in "1,2,10" && getString("incomeStatus") == "1"

            settingLocation.isChecked = getBoolean("isLocation")

            settingVoice.isChecked = (mAppData?.notifyEnable ?: "1") == "1"

            settingCall.isChecked = (mAppData?.callTelEnable ?: "1") == "1"

            settingVersionHint.text = "v${BaseViewModel.mVersion}"

            settingCache
                .setRightString(
                    GlideCacheUtil
                        .getInstance()
                        .getAllCacheSize(baseContext)
                )

            getViewModel()
                .checkUpdate(
                    context = baseContext,
                    slience = true,
                    show = false,
                    onNext = {
                        settingVersionImg.visible()
                    }
                )
        }
    }

    private fun initLauncher() {
        // 来电权限申请
        mLauncherCall =
            requestForPermission { result ->
                result.conditionElse(
                    actionTrue = {
                        mAppData?.let {
                            it.callTelEnable = "1"
                            mBinding.settingCall.isChecked = true

                            getBox<AppLoginData>().put(it)
                        }
                    },
                    actionFalse = ::showCallDeniedDialog
                )
            }

        mLauncher1 = requestForMultiplePermission(
            onGranted = {
                (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
                    .conditionElse(
                        actionTrue = {
                            mLauncher2
                                .launch(
                                    "android.permission.ACCESS_BACKGROUND_LOCATION"
                                )
                        },
                        actionFalse = { openLocation() }
                    )
            },
            onAlwaysDenied = { showDeniedDialog() }
        )

        mLauncher2 = requestForPermission {
            openLocation()

            it.conditionFalse {
                showOneHintDialog(
                    hint = getString(R.string.hint_always),
                    sure = "去设置"
                ) { goIntentSetting() }
            }
        }
    }

    @SuppressLint("MissingPermission")
    override fun initListener() {
        mAppData = getBoxEuery<AppLoginData>()
            .equal(AppLoginData_.isLogin, true)
            .build()
            .findFirst()

        mBinding.apply {
            // 打印JSESSIONID
            settingImg.oneClick {
                OkLogger.i(
                    OkGo.getInstance()
                        .cookieJar
                        .cookieStore
                        .allCookie
                        .toString()
                )

                LogcatHelper.i(osBandName())
                LogcatHelper.i(Build.VERSION.RELEASE)
                LogcatHelper.i(Build.MODEL)
            }

            // 快捷后台设置
            settingPermission.oneClick {
                startActivityEx<SettingLimitActivity>()
            }

            // 品牌权限设置
            settingNotice.oneClick {
                startActivityEx<SettingBrandActivity>()
            }

            // 第三方SDK
            settingSdk.oneClick {
                startActivityEx<WebActivity>("title" to "第三方SDK目录")
            }

            // 新手教程
            settingCourse.oneClick {
                startActivityEx<WebActivity>("title" to "使用教程")
            }

            // 实时位置
            settingLocation.oneTouch {
                getBoolean("isLocation")
                    .conditionElse(
                        actionTrue = {
                            (getVerCode().toInt() < 685)
                                .conditionElse(
                                    actionTrue = {
                                        // 关闭高德定位
                                        AMapLocationHelper
                                            .getInstance(baseContext)
                                            .stopLocation()
                                    },
                                    actionFalse = {
                                        // 关闭GPS定位
                                        LocationManager
                                            .instance
                                            .disableLocation()
                                    }
                                )

                            settingLocation.isChecked = false
                            putShared("isLocation", false)

                            getViewModel()
                                .request(
                                    isLoadingBefore = false,
                                    isLoadingAfter = false,
                                    isFailed = false,
                                    requestUrl = BaseUrl.clear
                                )
                        },
                        actionFalse = ::requestPermission
                    )
            }

            // 本地消息提示音
            settingVoice.oneTouch {
                mAppData?.let {
                    it.notifyEnable =
                        conditionIf(settingVoice.isChecked, "0", "1")

                    settingVoice.isChecked = it.notifyEnable == "1"

                    getBox<AppLoginData>().put(it)
                }
            }

            // 本地来电接单
            settingCall.oneTouch {
                settingCall.isChecked
                    .conditionElse(
                        actionTrue = {
                            mAppData?.let {
                                it.callTelEnable = "0"
                                settingCall.isChecked = false

                                getBox<AppLoginData>().put(it)
                            }
                        },
                        actionFalse = {
                            mLauncherCall
                                .launch(
                                    Manifest.permission.READ_CALL_LOG
                                )
                        }
                    )
            }

            // 版本更新
            settingVersion.oneClick {
                getViewModel().checkUpdate(baseContext)
            }

            // 清除缓存
            settingCache.oneClick {
                showHintDialog(
                    title = "清空缓存",
                    hint = "确定要清空缓存吗？",
                    onSure = {
                        showToast("清理成功！")

                        GlideCacheUtil
                            .getInstance()
                            .clearImageAllCache(baseContext)
                        mBinding
                            .settingCache
                            .setRightString("0B")
                    }
                )
            }

            // 退出登录
            btQuit.oneClick {
                showHintDialog(
                    title = "退出登录",
                    hint = "确定要退出登录吗？",
                    sure = "退出",
                    onSure = {
                        logout {
                            onSuccess {
                                OkLogger.i("腾讯云即时通讯退出登录！")
                                startActivityEx<LoginActivity>("offLine" to true)
                            }
                        }
                    }
                )
            }
        }

    }

    /**
     * 定位权限申请
     */
    @SuppressLint("MissingPermission")
    private fun requestPermission() {
        val list = when {
            Build.VERSION.SDK_INT <= Build.VERSION_CODES.P -> {
                arrayOf(
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION
                )
            }

            Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> {
                arrayOf(
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION
                )
            }

            else -> {
                arrayOf(
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    "android.permission.ACCESS_BACKGROUND_LOCATION"
                )
            }
        }

        mLauncher1.launch(list)
    }

    /**
     * 开启定位
     */
    @SuppressLint("MissingPermission")
    private fun openLocation() {
        (getVerCode().toInt() < 685)
            .conditionElse(
                actionTrue = {
                    // 开启高德定位
                    AMapLocationHelper
                        .getInstance(baseContext)
                        .startLocation()
                },
                actionFalse = {
                    // 开启GPS定位
                    LocationManager
                        .instance
                        .enableLocation()
                }
            )

        mBinding.settingLocation.isChecked = true
        putShared("isLocation", true)
    }

    /**
     * 定位权限禁止显示后提示操作
     */
    private fun showDeniedDialog() {
        showHintDialog(
            title = "提示",
            hint = "位置权限被禁止开启，请前往设置页面手动开启",
            sure = "去设置",
            cancel = "再想想",
            isForced = true,
            onSure = { goIntentSetting() }
        )
    }

    /**
     * 电话权限禁止显示后提示操作
     */
    private fun showCallDeniedDialog() {
        showHintDialog(
            title = "提示",
            hint = "通话记录权限被禁止开启，请前往设置页面手动开启",
            sure = "去设置",
            cancel = "再想想",
            isForced = true,
            onSure = { goIntentSetting() }
        )
    }

}